#include "Usart1_Process.h" //串口处理
#include "string.h"

//#include "usart.h"

#if USE_UART_1
extern uint8_t USART1_RX_BUF[USART1_REC_LEN];
#endif

#if USE_UART_2
extern uint8_t USART2_RX_BUF[USART1_REC_LEN];
#endif

#if USE_UART_1
uint32_t USART1_WRITE = 0;
uint32_t USART1_READ = 0;
#endif

#if USE_UART_2
uint32_t USART2_WRITE = 0;
uint32_t USART2_READ = 0;
#endif

#if USE_UART_1

uint8_t PACK_HEAD = 0xAA;
uint8_t PACK_END = 0x55;

void set_pack_head(uint8_t head)
{
    PACK_HEAD = head;
}
void set_pack_tail(uint8_t tail)
{
    PACK_END = tail;
}


uint16_t usart1_process(uint8_t *data_buf, uint16_t len)
{
	uint16_t i = 0;
	while (USART1_READ != USART1_WRITE)
	{
		uint8_t data = USART1_RX_BUF[USART1_READ & (USART1_REC_LEN - 1)];
		USART1_READ++;

		// 把串口缓存的数据拷贝到
		if (i < len)
		{
			data_buf[i++] = data;
			if (data == PACK_END)
			{
				return i;
            }else if(data == PACK_HEAD){
                i = 0;
                data_buf[i++] = data;
            }
		}
		else
		{
			return i;
		}
		// printf("%X ",data);
	}
	return i;
	// memset((char *)USART1_RX_BUF,'\0',USART1_REC_LEN);
}
#endif

#if USE_UART_2
void usart2_process(void)
{
	uint8_t i = 0;
	while (USART2_READ != USART2_WRITE)
	{
		uint8_t data = USART2_RX_BUF[USART2_READ & (USART2_REC_LEN - 1)];
		USART2_READ++;

		// 把串口缓存的数据拷贝到
		if (i < PACK_LENTH)
		{
			g_host_download_buf[i++] = data;
		}
		// printf("%X ",data);
	}
	// memset((char *)USART1_RX_BUF,'\0',USART1_REC_LEN);
}
#endif

#if USE_UART_1
/**
 * 判断串口是否在接收
 */
uint8_t usart1_available(void)
{
	static uint16_t data_index = 0;

	if (USART1_READ != USART1_WRITE)
	{ // 有数据
		if (data_index == USART1_WRITE)
		{
			data_index = 0;
			return DATA_WAIT_READ;
		}
		else
		{
			data_index = USART1_WRITE;
			return DATA_RECVING;
		}
	}
	return DATA_IS_NULL;
}
/**
 * 判断串口是否还有数据没读取完
 */
uint8_t usart1_read_able(void)
{
	if (USART1_READ != USART1_WRITE)
	{
		return 1;
	}
	return 0;
}

void usart1_flush(void)
{
    memset(USART1_RX_BUF, 0, sizeof(USART1_RX_BUF));
    USART1_WRITE = 0;
    USART1_READ = USART1_WRITE;
}

#endif

#if USE_UART_2
uint8_t usart2_available(void)
{
	static uint16_t data_index = 0;

	if (USART2_READ != USART2_WRITE)
	{ // 有数据
		if (data_index == USART2_WRITE)
		{
			data_index = 0;
			return DATA_WAIT_READ;
		}
		else
		{
			data_index = USART2_WRITE;
			return DATA_RECVING;
		}
	}
	return DATA_IS_NULL;
}
#endif
